﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CivitaiCLI.Utils
{
    public static class IOUtil
    {
        private static readonly char[] defaultTrimChars = { ' ' };
        public static string RemoveIllegalPathCharacters(string source, char[] trimChars = null, string replacement = "")
        {
            trimChars = trimChars ?? defaultTrimChars;
            string rgPattern = @"[\\\/:\*\?""<>|]";
            Regex objRegEx = new Regex(rgPattern);
            string result = objRegEx.Replace(source, replacement);
            if (trimChars.Length > 0) result = result.Trim(trimChars);
            return result;
        }

        public static string ExtractExtension(string val)
        {
            int lastPeriodIndex = val.LastIndexOf('.');
            return lastPeriodIndex == -1 ? "" : val.Substring(lastPeriodIndex);
        }

        public static bool TryFormatAbsolutePath(ref string workingDir)
        {
            if (Uri.TryCreate(workingDir, UriKind.RelativeOrAbsolute, out Uri uri))
            {
                if (!uri.IsAbsoluteUri && Uri.TryCreate(new Uri(Environment.CurrentDirectory + "\\"), workingDir, out Uri uriAbsolute) && uriAbsolute.Scheme == "file")
                {
                    workingDir = uriAbsolute.LocalPath;
                    return true;
                }
                else if (uri.Scheme == "file")
                {
                    workingDir = uri.LocalPath;
                    return true;
                }
                else
                {
                    return false;
                }
            }

            return false;
        }
    }
}
